package org.cancan.demo.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketResponse;
import com.aliyun.dingtalkoauth2_1_0.models.CreateJsapiTicketResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import org.cancan.demo.service.DingH5Service;
import org.cancan.demo.util.DdConfigSign;
import org.cancan.demo.vo.DingConfigSignVo;
import org.cancan.demo.vo.DingUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ding-h5")
public class DingH5Controller {

    @Value("${dingtalk.agentId}")
    private String agentId;

    @Value("${dingtalk.corpId}")
    private String corpId;

    @Value("${dingtalk.appKey}")
    private String appKey;

    @Value("${dingtalk.urlPath}")
    private String urlPath;

    @Autowired
    private DingH5Service dingH5Service;

    /**
     * 获取签名
     * @param dingConfigSignVo
     * @param request
     * @return
     */
    @PostMapping("/signAll")
    public ResponseEntity<Object> signAll(@RequestBody DingConfigSignVo dingConfigSignVo, HttpServletRequest request){
        //String urlString = request.getRequestURL().toString();
        //String queryString = request.getQueryString();
        //String queryStringEncode;
        //String url;
        //if (queryString != null) {
        //    queryStringEncode = URLDecoder.decode(queryString);
        //    url = urlString + "?" + queryStringEncode;
        //} else {
        //    url = urlString;
        //}
        String sign = null;
        String signedUrl = urlPath;
        String jticket =  dingH5Service.getJsapiTicket();
        dingConfigSignVo.setJsticket(jticket);
        Map<String, Object> jMap = new HashMap<>();
        try {
            sign = DdConfigSign.sign(dingConfigSignVo.getJsticket(),dingConfigSignVo.getNonceStr(),dingConfigSignVo.getTimeStamp(),signedUrl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        jMap.put("agentId",agentId);
        jMap.put("corpId",corpId);
        jMap.put("appKey",appKey);
        jMap.put("sign",sign);
        return new ResponseEntity<>(jMap, HttpStatus.OK);
    }

    /**
     * 根据code获取用户信息
     * @param code
     * @return
     */
    @GetMapping("/getUserByCode")
    public ResponseEntity<Object> getUserByCode(String code){
        DingUserInfo userByCode = dingH5Service.getUserByCode(code);
        return new ResponseEntity<>(userByCode, HttpStatus.OK);
    }

}
